package cn.jinbyte.web.filter;


import cn.jinbyte.web.config.SecurityHeaderProperties;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 安全响应头过滤器，基于配置文件参数设置安全响应头
 */
public class SecurityHeadersFilter implements Filter {

    private final SecurityHeaderProperties securityHeaderProperties;

    public SecurityHeadersFilter(SecurityHeaderProperties securityHeaderProperties) {
        this.securityHeaderProperties = securityHeaderProperties;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 如果安全响应头未启用，直接放行
        if (!securityHeaderProperties.isEnabled()) {
            chain.doFilter(request, response);
            return;
        }

        // 设置Content-Security-Policy头
        httpResponse.setHeader("Content-Security-Policy", securityHeaderProperties.getContentSecurityPolicy());

        // 设置X-XSS-Protection头
        httpResponse.setHeader("X-XSS-Protection", securityHeaderProperties.getXssProtection());

        // 设置X-Frame-Options头
        httpResponse.setHeader("X-Frame-Options", securityHeaderProperties.getXFrameOptions());

        // 设置X-Content-Type-Options头
        httpResponse.setHeader("X-Content-Type-Options", securityHeaderProperties.getContentTypeOptions());

        // 设置Referrer-Policy头
        httpResponse.setHeader("Referrer-Policy", securityHeaderProperties.getReferrerPolicy());

        // 设置Permissions-Policy头
        httpResponse.setHeader("Permissions-Policy", securityHeaderProperties.getPermissionsPolicy());

        chain.doFilter(request, response);
    }
}
